<?php
class ShoppingCartAction extends LoginFilterAction {

	
	public function index() {
		$str = "select b.pro_unit_name,a.id,b.name,b.id as product_id,b.local_price,b.imageurl_small, b.imageurl_big,a.quantity,a.lumpsum from shoppingcart a , viewproduct b 
		where a.product_id = b.id and a.user_name = '" .Session::get(C('USER_AUTH_KEY'))."'order by a.createdate desc";
		//dump($this->CommonSimplequery(1,$str));		
		$this->assign( "list" , $this->CommonSimplequery(1,$str))  ;
		
		 // 获取购物车产品数：
		/* 
		$str_count = "select count(1) as count from shoppingcart a , product b 
		where a.product_id = b.id and a.user_name = '" .Session::get(C('USER_AUTH_KEY'))."'order by a.createdate desc"; 
		$count = $this->CommonSimplequery(1,$str_count);
		dump($count[0]);
		*/
		$shoppingCondition['user_name'] =  $_SESSION[C('USER_AUTH_KEY')] ;		
	    $this->assign('shoppingCount',count($this->simpleQuery($shoppingCondition,'shoppingcart',0)));		
		$this->display();
	}
	

	
	
	/**
	 * 
	 *	清空/删除购物车记录
	 */
	public function deleteShoppingCart(){
		$Dao = M("shoppingcart");
		//清空整个购物车
		if(empty($_REQUEST ['id'])){				    
		    $result = $Dao->where("user_name = '" . Session::get(C('USER_AUTH_KEY')) . "'"  )->delete();
		}
		//删除单个购物记录
		else{
			$result = $Dao->where("id = '" . $_REQUEST ['id'] . "'"  )->delete();
		}
		if ($result !== false) {			
				$this->assign("jumpUrl","__URL__/index/");			
				$this->success ( "删除购物车成功" );
			}else{
				$this->success($model->getError ()) ;
		}
		
	}
	
	/**
	 * 更新购物车记录
	 * 
	 */
	public function updateShoppingCart(){
		//dump($_REQUEST ['id']);
		$Dao = M('shoppingcart');

	    // 需要更新的数据
	    $data['quantity'] = $_REQUEST ['quantity'];
	    $data['lumpsum'] = $_REQUEST ['lumpsum'];
	    // 更新的条件
	    $condition['id'] = $_REQUEST ['id'];
	    $result = $Dao->where($condition)->save($data);
	}
	
	/**
	 * 
	 * 产生订单页面
	 */
	public function shoppingOrder(){
		
		
		$queryString = "select a.id,b.id as product_id,b.name,b.imageurl_small,b.local_price,a.quantity,a.lumpsum from shoppingcart a , product b 
		where a.product_id = b.id and a.id in (" . $this->getProductOrderList() . ") and a.user_name = '" . Session::get(C('USER_AUTH_KEY')). "'order by a.createdate desc";	
				
		
		//dump($this->CommonSimplequery(1,$queryString));
		$this->assign( "list" , $this->CommonSimplequery(1,$queryString))  ;
		
		$this->assign('productcount',$_REQUEST['productcount']);
		$this->assign('totlecount',$_REQUEST['totlecount']);		
		
		$userCondition['name'] = $_SESSION[C('USER_AUTH_KEY')];		
		$this->assign('userVo',$this->simpleQuery($userCondition, 'loginuser',1));
		
		$this->display();
	}
	
	private function getProductOrderList(){
		$tempArray = $_REQUEST ['andy']  ;		
		$inString = "";		
		for ($i = 0 ; $i < count($tempArray) ; $i++){			
			if( $i!=0 ){
				$inString = $inString . "," ;
			}
			$inString = $inString . $tempArray[$i] ;
		}
		return $inString ;
	}
	
	private function getProductOrderName(){
		$tempArray = $_REQUEST ['god']  ;		
		$inString = "";		
		for ($i = 0 ; $i < count($tempArray) ; $i++){			
			if( $i!=0 ){
				$inString = $inString . "," ;
			}
			$inString = $inString . $tempArray[$i] ;
		}
		return $inString ;
	}
	
	/**
	 * 
	 * 保存订单并且给网站管理员发送订单邮件
	 */
	public function saveOrder(){
		
		//写入订单表
		$Dao = M('user_order');	
		$order_id = date('ymdHis').rand(1000,2000) ;

	    
		
		//根据session查询用户
		
	    $userCondition['name'] = Session::get(C('USER_AUTH_KEY')) ;
	    $user = $this->simpleQuery($userCondition,'loginuser',1);
		
		
		//发送邮件		
		
		$mailStr = '<table width="650" border="0" cellspacing="0" cellpadding="10" style="margin:0 auto;font-size:12px;">
		<tr>
			<td colspan="6"></td>
		</tr> 
		<tr>
			<td colspan="6"><p><strong>亲爱的：' . $user['name'] .  '， 感谢您的订购!</strong></p><p><strong>如何查看或修改您的订单？</strong><br />
    		如果您要查看或修改您的订单，请登录<a href="#">我的账户（点击跳到网站用户登录页）</a>。</p></td>
   		</tr>
 		<tr>
   			<td colspan="6" bgcolor="#009900" style="color:#ffffff;border:solid #009900 1px;"><strong>订购信息：</strong></td>
		</tr>
		<tr>
			<td colspan="6" style="border-left:solid #009900 1px;border-right:solid #009900 1px;border-bottom:solid #009900 1px;"><p><strong>订&nbsp;&nbsp;单&nbsp;&nbsp;号：'.$order_id . '
			</strong></p><p><strong>收货地址：' . $user['address'] . '</strong>'//收货地址
		.'</p><p><strong>订单总额：￥' . $_REQUEST['totlecount'] . '</strong>'//订单总额
		.'</p></td>
		</tr>
		<tr>
			<td colspan="6" bgcolor="#009900" style="color:#ffffff;border-left:solid #009900 1px;border-right:solid #009900 1px;border-bottom:solid #009900 1px;"><strong>商品详情：</strong></td>
 		</tr>
		<tr>			
			<td align="center" bgcolor="#DDFFCA" style="border-bottom:solid #009900 1px;border-left:solid #009900 1px;">商品名称</td>			
			<td align="center" bgcolor="#DDFFCA" style="border-bottom:solid #009900 1px;">数量（件）</td>
			<td align="center" bgcolor="#DDFFCA" style="border-bottom:solid #009900 1px;">单价（￥）</td>
			<td align="center" bgcolor="#DDFFCA" style="border-bottom:solid #009900 1px;border-right:solid #009900 1px;">总价（￥）</td>
		</tr>'//下面开始循环
		;
			
			$tempArray = $_REQUEST ['andy']  ;		
			$tempquantityList = $$_REQUEST ['quantityList']  ;
			$inString = "";		
			
			$productDao = M("product");
			
			for ($i = 0 ; $i < count($tempArray) ; $i++){
				$condition['id'] = 	$tempArray[$i];
				$shoppingcondition['product_id'] = 	$tempArray[$i];
				$product = $this->simpleQuery($condition, 'product',1); 
				$shoppingcart = $this->simpleQuery($shoppingcondition, 'shoppingcart',1);
				
				//更新相关产品信息
				//1、更新产品数量
				$productData['quantity'] = $product['quantity'] - $shoppingcart['quantity'] ;
				
				//2、更新产品销量
				$productData['salesamount'] = $productData['salesamount'] + 1 ;				
				$productDao->where($condition)->save($productData);
				
				$mailStr = $mailStr . '<tr> <td align="center" style="border-bottom:solid #009900 1px;border-left:solid #009900 1px;">' . $product['name'] //商品名称				
				.'</td><td align="center" style="border-bottom:solid #009900 1px;">' . $shoppingcart['quantity'] //商品数量
				.'</td><td align="center" style="border-bottom:solid #009900 1px;">' . $product['local_price'] //商品单价
				.'</td><td align="center" style="border-bottom:solid #009900 1px;border-right:solid #009900 1px;">' . ($shoppingcart['quantity'] * $product['local_price'])//商品总价
				.'</td></tr> ' ;				
			}
			
			
			
		$mailStr = $mailStr . '</tr>'
	
			.'<td colspan="6" align="center" style="border-bottom:solid #009900 1px;border-left:solid #009900 1px;border-right:solid #009900 1px;">商品总数：<strong style="color:#F60;">'//订单商品总数
			.'</strong> '. $_REQUEST['productcount'] .'件  总金额：<strong style="color:#F60;">￥' . $_REQUEST['totlecount']  //订单总金额
			.'</strong></td>
			
		</tr>
		<tr>
			<td colspan="6" align="left" style="border-bottom:solid #009900 1px;border-left:solid #009900 1px;border-right:solid #009900 1px;"><p><strong>此订单确认信仅确认我们已收到了您的订单，只有当我们向您发出产品时，我们和您之间的订购合同才成立。</strong></p>
     	 <p><br />
        了解更多信息，请访问&ldquo;<a href="#">帮助中心</a>&rdquo;。?<br />
     	 </p>
     	 <p>请注意: 此邮件发送地址仅用于发送订单信息，不能够接收邮件，请不要直接回复。</p>
     	 <p>欢迎您再次到<a href="#">万州特色农产品网</a>购物，祝您购物愉快！</p></td>
  		</tr>
		</table>' ;

		
		$data["order_id"] =  $order_id;
		$data["product_id_list"] = $this->getProductOrderList();
		$data["product_id_name"] = $this->getProductOrderName();
		
	    $data["user_name"] = Session::get(C('USER_AUTH_KEY')) ;
	    
	    //状态为1表示已提交，未处理的订单
	    $data["status"] = 1 ;	    	    
	    $data["order_content"] = $mailStr ;
	    $data["createdate"] = date('Y-m-d H:i:s',time());
	    $data["totlecount"] = $_REQUEST['totlecount'];
	    
	    
	    //写入数据
	    $Dao->add($data);		
	    
	    $sendResult = SendMail($user['email'],"邮件标题",$mailStr);
	    
	    //删除购物车的数据
	    $Dao = M("shoppingcart");	    
	    $result = $Dao->where("user_name = '".Session::get(C('USER_AUTH_KEY')) ."'")->delete();
	    
	    
		if ($sendResult) {
			//注册后跳转至首页
			$this->assign("jumpUrl","__APP__/UserCenter/");
			$this->success ( "提交订单成功，已发送订购邮件到您的注册邮箱中，请注意查收！" );
		}else{
			$this->success($model->getError ()) ;
		}
	}
	
	public function saveOrder_demo(){
		SendMail('303491711@qq.com',"邮件标题",'你好！');
		SendMail('43475085@qq.com',"邮件标题",'你好！');
		
	}

}
?>
